package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.common.BaseContext;
import com.ruan.common.Code;
import com.ruan.common.MessageConstant;
import com.ruan.common.Result;
import com.ruan.mapper.AdminMapper;
import com.ruan.pojo.Admin;
import com.ruan.pojo.CommonUser;
import com.ruan.service.AdminService;
//import com.ruan.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.util.Map;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper,Admin> implements AdminService {

    @Resource
    private AdminService adminService;

//    @Autowired
//    private JwtTokenUtil jwtTokenUtil;

    /**
     * 管理员登录
     * @param admin 管理员对象
     * @return
     */
    @Override
    public Result adminLogin(Admin admin) {

        //1、将页面提交的密码进行MD5加密处理
        String password=admin.getPassword();
//        password= DigestUtils.md5DigestAsHex(password.getBytes()).trim();
        //2、根据页面提交的用户名查询管理员数据库
        LambdaQueryWrapper<Admin> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,admin.getUsername()+"adminRole");

        Admin adminQuery = adminService.getOne(queryWrapper);
        //防止刷新后退出登录
        // 检查用户信息，生成登录令牌Token
//        String token = jwtTokenUtil.generateToken(adminQuery.getUsername());

//        Map<String, Object> responseData = new HashMap<>();
//        responseData.put("adminQuery", adminQuery);
//        responseData.put("token", token);

        //3、没有查到，登录失败
        if (adminQuery == null){
            //log.info("用户名不存在");
            return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_PASS);
        }
        queryWrapper.eq(Admin::getStatus,Admin.Status.waitForCheck);
        Admin adminQuery1 = adminService.getOne(queryWrapper);
        if(adminQuery1 != null){
            return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_AUDIT);
        }
        //4、密码对比，不一致，失败
        if (!password.equals(adminQuery.getPassword())){
            //log.info("密码错误");
            return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_PASS);
        }
        return new Result(Code.LOGIN_OK,adminQuery, MessageConstant.LOGIN_OK);
    }

}
